import csm_config_parser
import MainFrom
import wx
import wx.grid
import os
import sys
import logging
import csv
import _thread
# import re
# from xml.etree.ElementTree import ElementTree,Element,tostring
from lxml import etree

sys.path.extend([os.path.dirname(__file__)])
__logger = logging.getLogger(__name__)


class FileDrop(wx.FileDropTarget):
    def __init__(self, grid: wx.grid.Grid):
        wx.FileDropTarget.__init__(self)
        self.grid = grid

    def OnDropFiles(self, x, y, filenames):
        cell_coord = self.grid.XYToCell(x, y)
        row = cell_coord.GetRow()
        if row == -1:
            row = self.grid.GetNumberRows()
            self.grid.AppendRows(len(filenames))
        else:
            if (self.grid.GetNumberRows() - cell_coord.GetRow()) < len(filenames):
                self.grid.AppendRows(len(filenames) - self.grid.GetNumberRows() + cell_coord.GetROW())
        # filename = os.path.basename(filenames[0])

        for item in filenames:
            self.grid.SetCellValue(row, 0, item)
            row += 1
        self.grid.AutoSizeColumn(0)

        return True


def sub_thread_generate(grid: wx.grid.Grid, textCtrl: wx.TextCtrl):
    for i in range(grid.GetNumberRows()):
        if grid.GetCellValue(i, 0) != '':
            result = csm_config_parser.auto_generate(grid.GetCellValue(i, 0),
                                                     grid.GetCellValue(i, 1),
                                                     grid.GetCellValue(i, 2),
                                                     grid.GetCellValue(i, 3),
                                                     textCtrl.GetValue())
            if result is not None:
                grid.SetCellValue(i, 4, '完成')
            else:
                grid.SetCellValue(i, 4, '失败')


class MyMainWindow(MainFrom.MainForm):
    def __init__(self, parent):
        MainFrom.MainForm.__init__(self, parent)

        self.m_textCtrl1.SetValue(os.path.abspath('.'))
        self.m_textCtrl1.SetToolTip("双击左键选择要保存数据的目录！")
        self.m_grid1.SetToolTip("可直接拖拽配置文件目录到此！")
        # self.m_grid1.AppendRows(5)
        self.Bind(wx.EVT_CLOSE, self.on_close)
        self.filedrop = FileDrop(self.m_grid1)
        self.m_grid1.SetDropTarget(self.filedrop)
        # icon = wx.Icon(os.path.abspath('./Icon.png'), wx.BITMAP_TYPE_PNG)
        # self.SetIcon(icon)
        self.m_grid1.SetSelectionMode(wx.grid.Grid.GridSelectRows)
        self.station_name_dict = {}
        self.author_date_dict = {}

    def output_directory(self, event):
        __dlg = wx.DirDialog(self, message='请选择数据记录表生成目录', defaultPath=self.m_textCtrl1.Value)
        if __dlg.ShowModal() == wx.ID_OK:
            self.m_textCtrl1.SetValue(__dlg.GetPath())
        event.Skip()

    def generate_record(self, event):
        _thread.start_new_thread(sub_thread_generate, (self.m_grid1, self.m_textCtrl1))
        event.Skip()

    def Open_PopMenu(self, event):
        pos = event.GetPosition()
        # row = self.m_grid1.XYToCell(pos).GetRow()
        # print(row)
        # if row == -1:
        #     row = self.m_grid1.GetNumberRows()-1
        # else:
        #     row -= 1
        # print(row)
        # self.m_grid1.SelectRow(row)
        self.m_grid1.PopupMenu(self.m_menu1, pos)
        event.Skip()

    def OnDelRow(self, event):
        for index, row in enumerate(self.m_grid1.GetSelectedRows()):
            self.m_grid1.DeleteRows(row - index)
        event.Skip()

    def on_close(self, event):
        self.Destroy()

    def OnImportStationName(self, event):
        __dlg = wx.FileDialog(self, '请选择Station.xml配置文件：', defaultDir='Station.xml',
                              wildcard="xml file | *.xml")
        if __dlg.ShowModal() == wx.ID_OK:
            f = __dlg.GetPath()
            tree = etree.ElementTree(file=f)
            root = tree.getroot()
            self.station_name_dict.clear()
            for child in root.findall('.//Sta'):
                self.station_name_dict.update({child.attrib['telename']: child.attrib['name']})
            # print(self.station_name_dict)
            # print(self.m_grid1.GetNumberRows())
            # for row in range(self.m_grid1.GetNumberRows()):
            #     path = self.m_grid1.GetCellValue(row, 0)
            #     if os.path.isdir(path):
            #         name = os.path.basename(self.m_grid1.GetCellValue(row, 0))
            #         name_str = self.station_name_dict.get(name.split('_')[1])
            #         self.m_grid1.SetCellValue(row, 1, name_str)
            self.update_station_author_date()

        event.Skip()

    def OnExportConfig(self, event):
        __dlg = wx.FileDialog(self, "测试员和日期保存到：", defaultFile='测试人员和日期配置.csv', wildcard='csv file|*.csv',
                              style=wx.FD_SAVE)
        if __dlg.ShowModal() == wx.ID_OK:
            # print(__dlg.GetPath())
            with open(__dlg.GetPath(), 'w+', newline='') as f:
                csv_write = csv.writer(f)
                heads = ['车站名', '测试员', '日期']
                rows = []
                for i in range(self.m_grid1.GetNumberRows()):
                    if self.m_grid1.GetCellValue(i, 1) != '':
                        row = [self.m_grid1.GetCellValue(i, 1), self.m_grid1.GetCellValue(i, 2),
                               self.m_grid1.GetCellValue(i, 3)]
                        self.author_date_dict[row[0]] = row[1:]
                        rows.append(row)
                csv_write.writerow(heads)
                csv_write.writerows(rows)
            # print('self.author_date_dict:',self.author_date_dict)
            self.update_station_author_date()
        event.Skip()

    def update_station_author_date(self):
        for row in range(self.m_grid1.GetNumberRows()):
            cfg_path = self.m_grid1.GetCellValue(row, 0)
            if os.path.isdir(cfg_path) and cfg_path != '' and '_' in cfg_path:
                tele_name = os.path.basename(cfg_path).split('_')[1]
                if tele_name in self.station_name_dict.keys():
                    self.m_grid1.SetCellValue(row, 1, self.station_name_dict[tele_name])
            station_name = self.m_grid1.GetCellValue(row, 1)
            if station_name != '' and station_name in self.author_date_dict.keys():
                self.m_grid1.SetCellValue(row, 2, self.author_date_dict[station_name][0])
                self.m_grid1.SetCellValue(row, 3, self.author_date_dict[station_name][1])

    def OnImportAuthor(self, event):
        __dlg = wx.FileDialog(self, '选择要导入的测试员和日期配置文件：', wildcard='csv file|*.csv')
        if __dlg.ShowModal() == wx.ID_OK:
            self.author_date_dict.clear()
            with open(__dlg.GetPath(), 'r') as f:
                csv_read = csv.reader(f)
                for row in csv_read:
                    self.author_date_dict[row[0].strip()] = row[1:]
                del (self.author_date_dict['车站名'])
            # print('self.author_date_dict:', self.author_date_dict)
            self.update_station_author_date()


if __name__ == '__main__':
    app = wx.App()

    __FORMAT = "%(asctime)s  %(name)s %(levelname)s: %(message)s"
    logging.basicConfig(level=logging.WARNING, format=__FORMAT, datefmt="[%Y-%m-%d %H:%M:%S]")

    log = logging.getLogger('csm_config_parser')
    # log.propagate = False
    log.setLevel(logging.DEBUG)

    formatter = logging.Formatter(
        fmt="%(asctime)s %(name)s %(levelname)s %(message)s",
        datefmt="%Y-%m-%d %H:%M:%S"
    )
    fh = logging.FileHandler("cms_config_parser.log", encoding="utf-8")
    fh.setFormatter(formatter)
    ch = logging.StreamHandler()
    ch.setFormatter(fmt=formatter)
    # fh.setLevel(logging.DEBUG)
    log.addHandler(fh)

    dlg = MyMainWindow(None)
    # app.SetTopWindow(dlg)
    dlg.Show()
    app.MainLoop()

